/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.iaroc.irobot.sample;

import com.iaroc.irobot.util.KeyedStorage;

/**
 *
 * @author Mark
 */
public class MazeMapper extends Object
    {
    protected byte[][] map;
    protected String mapName;
    protected byte mapHor;
    protected byte mapVer;
    protected KeyedStorage ks;
    protected byte pathCounter;
    
    public final byte UNEXPLORED = -1;
    public final String mapDim = "Map Dimensions";
    public final String keys = "Key Row: ";
    
    public MazeMapper(String mapName, int mapHor, int mapVer)
        {
        super();
        if (mapHor < 0 || mapVer < 0)
            throw new IllegalArgumentException("Map Dimensions less than 0");
        map = new byte[mapVer][mapHor];
        if (mapName == null)
            throw new IllegalArgumentException("Map Name is null");
        this.mapName = mapName;
        ks = new KeyedStorage(this.mapName);
        for (byte i = 0; i < mapVer; i++)
            for (byte x = 0; x < mapHor; x++)
                map[mapVer][mapHor] = UNEXPLORED;
        //setting all unexplored
        pathCounter = 0;
        }
    
    public MazeMapper(String mapName)
        {
        super();
        ks = new KeyedStorage(mapName);
        if (ks.getBytes(mapDim) == null)
            throw new IllegalArgumentException("Map not stored, Wrong name of " +
                    "map");
        mapVer = ks.getBytes(mapDim)[0];
        mapHor = ks.getBytes(mapDim)[1];
        int row = 0;
        for (byte i = 0; i < mapVer; i++)
            {
            String key = keys + row++;
            byte[] lastRow = ks.getBytes(key);
            for (byte x = 0; x < mapHor; x++)
                map[mapVer][x] = lastRow[x];
            }
        }
    
    public boolean setNext(int x, int y)
        {
        if (x < 0 || x > mapHor || y < 0 || y > mapVer)
            return false;
        map[x][y] = pathCounter++;
        return true;
        }
    
    public String storeMap()
        {
        int row = 0;
        ks.putBytes(mapDim, new byte[] {mapVer, mapHor});
        byte[] store;
        for (byte i = 0; i < mapVer; i++)
            {
            store = new byte[mapHor];
            String key = keys + row++;
            for (byte x = 0; x < mapHor; x++)
                store[x] = map[mapVer][x];
            ks.putBytes(key, store);
            }
        return mapName;
        }
    
    }
